package com.example.video.util;

import com.example.video.entity.Account;
import com.example.video.service.impl.AccountServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.video.common.Result;
import com.example.video.entity.ResponseData;
import com.example.video.service.impl.VideoLogServiceImpl;
import com.example.video.service.impl.VideoServiceImpl;
import com.example.video.util.download.FileUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class HHdata {

    @Value("${HHuserid}")
    private String userId;

    @Value("${HHsecretKey}")
    private String secretKey;

    @Value("${downLoadPath}")
    private String downLoadPath;

    @Value("${ServerUrl}")
    private String serverUrl;

    @Resource
    private AccountServiceImpl accountService;

    @Resource
    private VideoServiceImpl videoService;

    @Resource
    private VideoLogServiceImpl videoLogService;

    /**
     * 获取AccountService
     * @return
     */
    public AccountServiceImpl getAccountService() {
        return accountService;
    }

    /**
     * 获取VideoService
     * @return
     */
    public VideoServiceImpl getVideoService() {
        return videoService;
    }

    /**
     * 获取downLoadPath
     * @return
     */
    public String getDownLoadPath() {
        return downLoadPath;
    }

    /**
     * 获取serverUrl
     * @return
     */
    public String getServerUrl() {
        return serverUrl;
    }



    /**
     * 重写crawlData
     * @param url           主页地址
     * @param next_cursor   下一批数据节点
     * @return
     */
    public Result<ResponseData> requestData( String url, String next_cursor) {
        Result<ResponseData> rs = new Result<>();
        String api = "https://h.aaaapp.cn/posts";
        // 测试
//        String api = "http://localhost:8080/test";
        // 获取当前时间
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化当前时间为年月日时间
        String formattedDate = dateFormat.format(currentDate);
        // 设置时区为东八区（中国标准时间）
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));


        try {
            // 创建参数对象
            JSONObject params = new JSONObject();
            params.put("userId", userId);
            params.put("secretKey", secretKey);
            params.put("url", url);
            params.put("cursor", next_cursor);

//             log.info("HHdata -> requestData -> msg: " + params.toString(5));
            // 创建 URL 对象
            URL apiUrl = new URL(api);
            // 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 开启输出模式
            connection.setDoOutput(true);

            // 获取输出流并写入参数数据
            OutputStream outputStream = connection.getOutputStream();
            // 使用 PrintWriter 并指定字符编码为 UTF-8
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            writer.print(params.toString());
            writer.flush();
            writer.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析 JSON 字符串
                JSONTokener tokener = new JSONTokener(response.toString());
                JSONObject jsonResponse = new JSONObject(tokener);

                // 创建 ObjectMapper 对象
                ObjectMapper objectMapper = new ObjectMapper();

                // 从文件中读取 JSON 数据并映射到 Java 对象
                ResponseData responseData = objectMapper.readValue(jsonResponse.toString(), ResponseData.class);
//                log.info("HHdata -> requestData -> msg : responseData : " + responseData);
                rs.setData(responseData);
                rs.setMsg("获取成功！");
                rs.setCount(1);
                rs.setCode(0);


            } else {
                // 输出错误信息
                System.err.println("HHdata -> requestData -> errMsg: HTTP request failed with code: " + responseCode);

                rs.setCount(0);
                rs.setCode(-1);
                rs.setMsg("responseCode: "+responseCode);
                rs.setData(null);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("HHdata -> requestData -> errMsg: " + e.getMessage());
            rs.setCode(-1);
            rs.setCount(0);
            rs.setMsg("HHdata -> requestData -> errMsg: "+e.getMessage());
            rs.setData(null);
        }
//        log.info("HHdata -> crawlData -> msg : 返回的数据 = "+rs);
        return rs;
    }


    /**
     * 爬取源作者数据并保存数据库。
     * 先连接爬虫接口，获取数据，通过对数据的处理，分别得到源作者信息和视频信息。再插入到数据库。
     * @deprecated
     * @param accountId 源作者id
     * @param url       源作者主页url
     * @return data:下一个cursor
     */
    @Deprecated
    public Result<String> crawlData(Integer accountId, String url, String next_cursor, Authentication authentication) {
        Result<String> rs = new Result<>();
        //log.info("id : "+id + "url :  "+url);
        //boolean result = true;
        // 测试
//        String api = "https://h.aaaapp.cn/posts";
        String api = "http://localhost:8080/test";
        // 获取当前时间
        Date currentDate = new Date();
        // 创建 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 格式化当前时间为年月日时间
        String formattedDate = dateFormat.format(currentDate);
        // 设置时区为东八区（中国标准时间）
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));


        try {
            // 创建参数对象
            JSONObject params = new JSONObject();
            params.put("userId", userId);
            params.put("secretKey", secretKey);
            params.put("url", url);
            params.put("cursor", next_cursor);

            // log.info("HHdata -> crawlData -> msg: " + params.toString(5));
            // 创建 URL 对象
            URL apiUrl = new URL(api);
            // 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 开启输出模式
            connection.setDoOutput(true);

            // 获取输出流并写入参数数据
            OutputStream outputStream = connection.getOutputStream();
            // 使用 PrintWriter 并指定字符编码为 UTF-8
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            writer.print(params.toString());
            writer.flush();
            writer.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));

                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析 JSON 字符串
                JSONTokener tokener = new JSONTokener(response.toString());
                JSONObject jsonResponse = new JSONObject(tokener);

                // 创建 ObjectMapper 对象
                ObjectMapper objectMapper = new ObjectMapper();

                // 从文件中读取 JSON 数据并映射到 Java 对象
                ResponseData responseData = objectMapper.readValue(jsonResponse.toString(), ResponseData.class);
//                log.info("HHdata -> crawlData -> msg : responseData : " + responseData);


                if (responseData.getCode() == 200) {
//                    保存源作者信息
                    if (responseData.getData().getUser() != null) {
                        Account account = accountService.getItem(accountId);
//                        log.info(account);
                        if (account != null) {
                            String name = responseData.getData().getUser().getUsername();
                            if (name == null || "".equals(name)) {
                                account.setName(UUID.randomUUID().toString());
                            } else {
                                account.setName(name);
                            }


                            File directory = new File(downLoadPath + account.getName() + "/" + formattedDate);
                            if (!directory.exists()) {
                                directory.mkdirs();
                            }

                            // 若未下载头像，则去下载并保存到用户目录下
                            if (account.getAvatarUrl() == null || "".equals(account.getAvatarUrl())) {
//                                log.info("HHdata -> crawlData -> msg : 首次或重新下载头像");

                                if (responseData.getData().getUser().getAvatar() != null && !"".equals(responseData.getData().getUser().getAvatar())) {

                                    FileUtil.downloadImage(responseData.getData().getUser().getAvatar(), downLoadPath + account.getName() + "/" + account.getName() + ".jpg");
                                    account.setAvatarUrl(serverUrl + account.getName() + "/" + account.getName() + ".jpg");
                                }

                            }
                            if ("no_more".equals(responseData.getData().getNext_cursor())) {
                                account.setNextCursor(next_cursor);
                            }
                            // 5.1 注释 如果nextcursor不相等，则添加总数
                            /*if(next_cursor == null || next_cursor.equals(responseData.getData().getNext_cursor()) ){
                                // 如果是第一次请求
                                if( account.getTotal() == 0){
                                    account.setTotal(responseData.getData().getPosts().size());
                                }
                            }else{

                            }*/
                            // 5.1 添加 -> 取消判断是否为第一次添加总数。在VideoSerImpl的addList中减去数据库中已有的数据即可
                            account.setTotal(account.getTotal() + responseData.getData().getPosts().size());
//                            log.info("HHdata -> crawlData -> msg :"+account.getTotal());
                            accountService.updateById(account);
                        } else {
                            rs.setCode(-1);
                            rs.setMsg("无该账号信息！");
                            rs.setData("no_more");
                        }
                    }

                    videoService.addList(responseData.getData(), accountId, next_cursor,authentication);
                    rs.setCode(0);
                    if (responseData.getData() != null) {
                        rs.setData(responseData.getData().getNext_cursor());
                    } else {
                        rs.setData(null);
                    }

                } else if (responseData.getCode() == 400) {
                    rs.setCode(-1);
                    if (responseData.getMsg() != null) {
                        rs.setMsg(responseData.getMsg());
                    } else {
                        rs.setMsg("请检查链接是否正确！");
                    }
                    rs.setData("no_more");
                } else if (responseData.getCode() == 300) {
                    rs.setCode(-2);
                    if (responseData.getMsg() != null) {
                        rs.setMsg(responseData.getMsg());
                    } else {
                        rs.setMsg("接口调用额度已用完，请充值再使用！");
                    }
                    rs.setData("no_more");
                }

            } else {
                // 输出错误信息
                log.info("HTTP request failed with code: " + responseCode);
                rs.setCode(-1);
                rs.setMsg("responseCode");
                rs.setData("no_more");
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            rs.setCode(-1);
            rs.setCount(0);
            rs.setMsg("源账户主页url错误！");
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            rs.setMsg("下载错误！");
            rs.setData("no_more");
        }
//        log.info("HHdata -> crawlData -> msg : 返回的数据 = "+rs);
        return rs;
    }


}
